package com.example.windows8.sinaweibo;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Windows 8 on 2017/6/20.
 */

public class Login extends AppCompatActivity implements View.OnClickListener{
    private Button login;
    private AuthInfo authInfo;
    private SsoHandler ssoHandler;
    private Oauth2AccessToken accessToken;
    private IWeiboShareAPI weiboShareAPI;
    private SinaUserInfo userInfo;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        weiboShareAPI = WeiboShareSDK.createWeiboAPI(this, Constants.APP_KEY);
        login = (Button)findViewById(R.id.login);
        login.setOnClickListener(this);
    }
    public void onClick (View v){
        authInfo = new AuthInfo(this, Constants.APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE);
        ssoHandler = new SsoHandler(Login.this, authInfo);
        ssoHandler.authorize(new AuthListener());
    }
    public class AuthListener implements WeiboAuthListener {

        @Override
        public void onCancel() {
            // TODO Auto-generated method stub
            Toast.makeText(Login.this, "授权取消", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onComplete(Bundle values) {
            // TODO Auto-generated method stub

            accessToken = Oauth2AccessToken.parseAccessToken(values); // 从Bundle中解析Token
            String phoneNum = accessToken.getPhoneNum();// 从这里获取用户输入的 电话号码信息

            if (accessToken.isSessionValid()) {

                AccessTokenKeeper.writeAccessToken(Login.this, accessToken); // 保存Token
                Toast.makeText(Login.this, "授权成功", Toast.LENGTH_SHORT)
                        .show();
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        UsersAPI usersAPI = new UsersAPI(Login.this, Constants.APP_KEY, accessToken);
                        usersAPI.show(Long.valueOf(accessToken.getUid()), new SinaRequestListener());

                    }
                }).start();
                Intent intent = new Intent(Login.this, SinaWeibo.class);
                startActivity(intent);
            }else{
// 以下几种情况，您会收到
// 1. 当您未在平台上注册的应用程序的包名与签名时；
// 2. 当您注册的应用程序包名与签名不正确时；
// 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。

                String code = values.getString("code");
                String message = "授权失败";
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code: " + code;
                }
                Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show();

            }

        }
        @Override public void onWeiboException(WeiboException e)
        {// TODO Auto-generated method stub

            Toast.makeText(Login.this, "Auth exception : " + e.getMessage(),Toast.LENGTH_LONG).show();
        }
    }

    public class SinaRequestListener implements RequestListener { //新浪微博请求接口
        @Override
        public void onComplete(String response) {// TODO Auto-generated method stub
            try {
                JSONObject jsonObject = new JSONObject(response);
                String idStr = jsonObject.getString("idstr");// 唯一标识符(uid)
                String name = jsonObject.getString("name");// 姓名
                String avatarHd = jsonObject.getString("avatar_hd");// 头像
                System.out.println(idStr + name + avatarHd);
                userInfo = new SinaUserInfo();
                userInfo.setUid(idStr);
                userInfo.setName(name);
                userInfo.setAvatarHd(avatarHd);
                Message message = Message.obtain();
                message.what = 1;
            } catch (JSONException e) {// TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onWeiboException(WeiboException e)
        {// TODO Auto-generated method stubToast.makeText(context, "Auth exception : " + e.getMessage(),Toast.LENGTH_LONG).show();
            Log.i("mylog", "Auth exception : " + e.getMessage());
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if(ssoHandler != null){
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }
}
